package org.example.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.rental.common.User;
import org.example.rental.domain.*;
import org.example.rental.domain.vo.ChartVo;
import org.example.rental.service.CarService;
import org.example.rental.service.RentalGoodsService;
import org.example.rental.service.RentalOrderService;
import org.example.rental.mapper.RentalOrderMapper;
import org.example.rental.support.ids.IIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
* @author xulongxing
* @description 针对表【rental_order(租赁订单表)】的数据库操作Service实现
* @createDate 2023-12-10 15:49:05
*/
@Service
public class RentalOrderServiceImpl extends ServiceImpl<RentalOrderMapper, RentalOrder>
    implements RentalOrderService{

    @Autowired
    User user;


    @Autowired
    CarService carService;

    @Autowired
    RentalGoodsService rentalGoodsService;

    @Autowired
    IIdGenerator snowFlake;



    @Transactional
    public void submitOrder(RentalOrder order) {
        SysUser sysUser = user.getSysUser();
        order.setUsername(sysUser.getUsername());
        order.setUserId(sysUser.getId());
        Car car = carService.getById(order.getCarId());
        RentalGoods goods = rentalGoodsService.getOne(new QueryWrapper<RentalGoods>().eq("veh_id", car.getVehId()));
        order.setHeadImg(goods.getHeadImg());
        order.setDescription(car.getBlurb());
        order.setCarNum(car.getCarNum());
        order.setName(car.getVehName());
        order.setStatus(0);
        order.setGoodsId(goods.getId());
        order.setModelNum(car.getModelNum());
        order.setOrderId(String.valueOf(snowFlake.nextId()));
        if (order.getLeaseMethod() == 0){ //日租
            // 计算租赁天数
            long diffInMillies = order.getReturnTime().getTime() - order.getRentalTime().getTime();
            long rentalDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
            order.setMonthNums((int) rentalDays);
            //费用计算 租赁费用+押金(租赁费用10%)
            double money = goods.getPrice() * rentalDays;
            order.setRent(money);
            order.setDeposit(money*0.1);
            order.setTotalMoney(order.getRent()+order.getDeposit());
        }else {
            //费用计算 租赁费用+押金(租赁费用10%)
            order.setRentalTime(new Date());
            Calendar calendar = Calendar.getInstance(); // 获取当前时间日期
            calendar.add(Calendar.MONTH, order.getMonthNums()); // 将当前时间日期增加n个月
            order.setReturnTime(calendar.getTime());
            double money = order.getMonthNums()*30*goods.getPrice();
            order.setRent(money);
            order.setDeposit(money*0.1);
            order.setTotalMoney(order.getRent()+order.getDeposit());
        }

        this.save(order);
        //修改状态
        car.setStatus(1);
        carService.updateById(car);
        //修改goods的租出车辆数
        goods.setUseSizes(goods.getUseSizes()==null?1:goods.getUseSizes()+1);
        rentalGoodsService.updateById(goods);

    }


    @Transactional
    public void cancelOrder(Integer id) {
        RentalOrder order = getById(id);
        //取消订单状态
        order.setStatus(-1);
        updateById(order);

        //修改车辆状态为闲置状态
        Car car = carService.getById(order.getCarId());
        car.setStatus(0);
        carService.updateById(car);

        //修改对应的车型租借数量
        RentalGoods goods = rentalGoodsService.getById(order.getGoodsId());
        goods.setUseSizes(goods.getUseSizes()-1);
        rentalGoodsService.updateById(goods);


    }

   //图表统计
    public ChartVo chart() {
        ChartVo chartVo = new ChartVo();
        String[] strings = getSevenTime();
        Integer[] integers = new Integer[7];
        for (int i = 0; i < strings.length; i++) {
            Integer data = baseMapper.chart(strings[i]);
            integers[i] = data == null?0:data;
        }
        chartVo.setTitles(strings);
        chartVo.setDatas(integers);

        Integer days = baseMapper.selectDayNums();
        Integer months = baseMapper.selectMonthNums();
        Integer totalNums = baseMapper.selectPayNums();
        Long totalPayMoney = baseMapper.selectPayMoney();
        chartVo.setCurrentDayNums(days);
        chartVo.setCurrentMonthNums(months);
        chartVo.setTotalPayNum(totalNums);
        chartVo.setTotalPayMoney(totalPayMoney);
        return chartVo;
    }



    public String[] getSevenTime(){
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 创建日期格式化器，指定日期格式为 "yyyy-MM-dd"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 创建一个长度为7的字符串数组，用于存储7天的日期（包括当前日期和前6天）
        String[] dateArray = new String[7];
        // 循环遍历前6天的日期，将每个日期格式化为 "yyyy-MM-dd" 的字符串
        for (int i = 0; i < 6; i++) {
            dateArray[i] = currentDate.minusDays(6 - i).format(formatter);
        }

        // 将当前日期格式化为 "yyyy-MM-dd" 的字符串并放入数组最后一位
        dateArray[6] = currentDate.format(formatter);
        return dateArray;
    }
}




